import React, {useEffect, useState} from "react";
import store from "../redux/store"
import style from "./css/Cinema.module.css";
import CinemaAction from "../action/CinemaAction";

export default function Cinema(props) {
    const [cinemaList, setCinemaList] = useState(store.getState().CinemaReducer.cinemaList);

    useEffect(() => {
        // Redux本身默认的dispatch方法只能接收一个普通的JS对象作为Action，Redux Thunk中间件可以检查dispatch方法接受的参数类型
        // 如果是一个普通对象，它就放行，让这个Action继续它的旅程（前往Reducer或其他中间件）
        // 如果是一个函数（这种函数就被称为"thunk"），Thunk中间件就会拦截这个函数，并且执行它，并将真正的dispatch方法作为参数传给你的thunk函数
        if (store.getState().CinemaReducer.cinemaList.length === 0) {
            store.dispatch(CinemaAction());
        } else {
            console.log("使用了缓存");
        }

        // 订阅影院数据
        const unSubscribe = store.subscribe(() => {
            console.log(store.getState().CinemaReducer.cinemaList);
            setCinemaList(store.getState().CinemaReducer.cinemaList)
        })
        return () => {
            // 离开组件取消订阅 解决重复订阅问题
            unSubscribe()
        }
    }, []);

    return <div>
        <div style={{display: "flex", justifyContent: "space-between", paddingLeft: "5px", paddingRight: "5px"}}>
            <div onClick={() => props.history.push("/city")}>
                {store.getState().CityReducer.city}
            </div>
            <div onClick={() => props.history.push("/cinema/search")}>搜索</div>
        </div>
        <div className={style['cinema-list']}>
            {cinemaList.map(cinema => {
                return <dl key={cinema.cinemaId}>
                    <dt>{cinema.name}</dt>
                    <dd>{cinema.address}</dd>
                </dl>
            })}
        </div>
    </div>
}